package com.lu.library

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.LogUtils
import com.lu.library.widget.ChoosePicDialog
import com.lyw.camera.PreviewActivity
import com.lyw.camera.PreviewCallback
import com.lyw.camera.PreviewManager
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 图片选择
 */
class ChoosePicManager(var activity: Activity,var onSelected:(Uri)->Unit) {
    private val REQUEST_IMAGE_CAPTURE = 1
    private val REQUEST_IMAGE_PICK = 2
    private  var currentPhotoPath: String?=null


    private val dialog:ChoosePicDialog = ChoosePicDialog(activity, onChoosePic = {
        if (checkPermissions()){
            dispatchPickPictureIntent()
        }
    },{
        if (checkPermissions()){
            dispatchTakePictureIntent()
        }
    }).also {
        it.setOnDismissListener {
            release()
        }
    }
    fun dismiss(){
        if (dialog.isShowing) {
            dialog.dismiss()
        }
    }
    fun showDialog(){
        if (!dialog.isShowing) {
            dialog.show()
        }
    }


     fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_IMAGE_CAPTURE -> {
                    val file = File(currentPhotoPath)
                    LogUtils.d(currentPhotoPath)
                    if (file.exists()) {
                        onSelected(Uri.fromFile(file))
                    }

                }
                REQUEST_IMAGE_PICK -> {
                    val selectedImage: Uri? = data?.data
                    LogUtils.d(selectedImage)
                    onSelected(selectedImage!!)
                }
            }
        }
    }
    private fun checkPermissions(): Boolean {
        val permissions = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
        )
        val listPermissionsNeeded = mutableListOf<String>()
        for (permission in permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(permission)
            }
        }
        if (listPermissionsNeeded.isNotEmpty()) {
            ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toTypedArray(), 0)
            return false
        }
        return true
    }
    private val callback =object:PreviewCallback{
        override fun takePicture(filePath: String) {
            onSelected(Uri.fromFile(File(filePath)))
            release()
        }
    }
   private fun release(){
       PreviewManager.unRegisterCallback(callback)
    }
    private fun dispatchTakePictureIntent() {
        PreviewManager.registerCallback(callback)
        PreviewManager.start(activity,createImageFile())

//        PreviewActivity.start(activity,createImageFile())
//        val openCameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // 系统常量， 启动相机的关键
//        ActivityCompat.startActivityForResult(activity,Intent(activity,PreviewActivity::class.java),null)
//        ActivityCompat.startActivityForResult(
//            activity,
//            openCameraIntent,
//            REQUEST_IMAGE_CAPTURE,null
//        ) // 参数常量为自定义的request code, 在取返回结果时有用

//        Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
//            LogUtils.d("resolveActivity")
//            takePictureIntent.resolveActivity(CommLibInit.getApp().packageManager)?.also {
//                val photoFile: File? = try {
//                    createImageFile()
//                } catch (ex: IOException) {
//                    null
//                }
//                LogUtils.d("createImageFile")
//                photoFile?.also {
//                    val photoURI: Uri = FileProvider.getUriForFile(
//                        CommLibInit.getApp(),
//                        CommLibInit.getApp().packageName+".provider",
//                        it
//                    )
//                    LogUtils.d("startActivityForResult ${it.absolutePath}")
//                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
//                    ActivityCompat.startActivityForResult(activity,takePictureIntent, REQUEST_IMAGE_CAPTURE,null)
//                }
//            }
//        }
    }
    private fun dispatchPickPictureIntent() {
        Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI).also { pickPictureIntent ->
            pickPictureIntent.type = "image/*"
            ActivityCompat.startActivityForResult(activity,pickPictureIntent, REQUEST_IMAGE_PICK,null)
        }
    }

    @Throws(IOException::class)
    private fun createImageFile(): File {
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date())+".png"
        val storageDir: File = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES)!!
        return File(storageDir,timeStamp).apply {
            currentPhotoPath = absolutePath
        }
    }
}